#!/usr/bin/python
from Bio import SeqIO
import sys
import re
import tms_compare
import tempfile

class scan:
	
	def __init__(self,subject,target,sss):
		subject = SeqIO.parse(subject,'fasta')
		target = SeqIO.parse(target,'fasta')
		self.subject=SeqIO.to_dict(subject)
		self.target=SeqIO.to_dict(target)
		self.target.update(self.subject)
		self.load_results(sss)
		
	def load_results(self,sss):
		keys = re.compile("(\w+)\s+\(\w+ \w+-\w+ \w+\)\s+(\w+)")
		output=open("./TMS_COMPARE.TXT","w+")
		for line in open(sss):
			symbols = keys.search(line).groups()
			subject_seq = self.target[symbols[0]]
			target_seq = self.target[symbols[1]]
			subject_file = tempfile.NamedTemporaryFile()
			SeqIO.write(subject_seq,subject_file,'fasta')
			target_file = tempfile.NamedTemporaryFile()
			SeqIO.write(target_seq,target_file,'fasta')
			subject_file.flush()
			target_file.flush()
			tmc = tms_compare.compare(subject_file.name,target_file.name)
			output.write("\n\n===========COMPARISON FOR ("+symbols[0]+" - "+symbols[1]+")======================\n\n")
			for score in tmc.scores:
				if score[0] < 2:
					continue
				key=str(score[1])+str(score[2])
				output.write("\nLAMBDA SCORE: "+str(score[0])+"\n")
				output.write("TMS COMPARED: "+str(score[1])+"-"+str(score[2])+"\n\nVIEW ALIGNMENT:\n")
				output.write(tmc.alignments[key]+"\n\n-------------------------------")
		output.seek(0)
		print output.read()			
		